package com.boil.qz.safekavass.websocket;

import com.boil.qz.safekavass.model.LoginUser;
import com.boil.util.Constants;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

import java.util.Map;

/**
 * Created by ChenYong on 2016-10-31.
 * <br>
 * WebSocket 拦截器。
 */
@Component
public class WebSocketInterceptor extends HttpSessionHandshakeInterceptor {
    /**
     * 日志
     */
    private static Logger log = LoggerFactory.getLogger(WebSocketInterceptor.class);

    /**
     * 默认构造器。
     */
    public WebSocketInterceptor() {
        super();
    }

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, //
                                   ServerHttpResponse response, //
                                   WebSocketHandler handler, //
                                   Map<String, Object> map) throws Exception {
        try {
            // 解决 Safari 浏览器不支持的问题
            if (request.getHeaders().containsKey("Sec-WebSocket-Extensions")) {
                request.getHeaders().set("Sec-WebSocket-Extensions", "permessage-deflate");
            }

            // 获取登录用户的操作信息
            Subject subject = SecurityUtils.getSubject();

            // 已经登录
            if (subject.isAuthenticated()) {
                // 获取 Session
                Session session = SecurityUtils.getSubject().getSession();
                // 获取登录用户
                LoginUser loginUser = (LoginUser) session.getAttribute(Constants.LOGIN_USER);

                map.put(Constants.LOGIN_USER, loginUser);
            }
        } catch (Exception e) {
            log.error("WebSocket 拦截器（beforeHandshake）出现异常，异常信息如下：{}", e);
        }

        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, //
                               ServerHttpResponse response, //
                               WebSocketHandler handler, //
                               Exception e) {
    }
}